import { editExpireApi, getDriverCardDetail } from '@/api/OfflineStudy';
import CusModal from '@/components/CusModal';
import { App, Button, Descriptions, Empty, message, Spin, Timeline } from 'antd';
import { isEmpty } from 'lodash-es';
import { useCallback, useEffect, useRef, useState } from 'react';
import EditExpireModal from './EditExpireModal';
import OStyle from './index.less';
function DriverCardDetail(props: { curCardId: string; refreshTable: () => void }) {
  console.log('DriverCardDetail', props);
  const { curCardId, refreshTable } = props;
  const [loading, setLoading] = useState(false);
  const [cardDetail, setCardDetail] = useState<Record<string, any>>();
  const [timeLineItems, setTimeLineItems] = useState<any>([]);
  const EditExpireRef = useRef<any>(null);
  const [configModal, setConfigModal] = useState<{ title: string; children: React.ReactNode }>();
  const [modalBtnStatus, setModalBtnStatus] = useState({ loading: false, disabled: false }); //modal框按钮状态
  const [isModalShow, setIsModalShow] = useState<{ show: boolean }>({ show: false });
  const {
    modal: { confirm },
  } = App.useApp();
  // 打开编辑过期时间
  const openEditExpirModal = (param: any) => {
    setIsModalShow({ show: true });
    setConfigModal({
      title: '更改有效期',
      children: <EditExpireModal ref={EditExpireRef} {...param} />,
    });
  };
  // 关闭modal
  const closeModal = () => {
    setIsModalShow({ show: false });
  };

  const setTimeLineItemsFn = useCallback((list: any) => {
    return list?.map((item: any, index: number) => ({
      key: index,
      color: '#F0F0F0',
      dot: <div className={OStyle.timeline_clock_icon}></div>,
      itemPaddingBottom: 32,
      children: (
        <div className="item_line_record_item" key={item.index}>
          <div className={OStyle.labelTime}>{item.labelTime}</div>
          <div className={OStyle.item_line_address}>{item.address}</div>
          <div className={`${OStyle.clock_info} flexr alc`}>
            <div className={`${OStyle.clock_info_item} flexr alc jub`}>
              <div className="flexr alc">
                <div className={OStyle.line}></div>
                <div className={OStyle.clockTime}>
                  <div className={OStyle.hms}>{item.signInTime.slice(11, 16)}</div>
                  <div className={OStyle.ymd}>{item.signInTime.slice(0, 10)}</div>
                </div>
              </div>
              <div className={OStyle.status}>已打卡</div>
            </div>
            {item.signOutTime ? (
              <div className={`${OStyle.clock_info_item} flexr alc jub`}>
                <div className="flexr alc">
                  <div className={OStyle.line}></div>
                  <div className={OStyle.clockTime}>
                    <div className={OStyle.hms}>{item.signOutTime.slice(11, 16)}</div>
                    <div className={OStyle.ymd}>{item.signOutTime.slice(0, 10)}</div>
                  </div>
                </div>
                <div className={OStyle.status}>已打卡</div>
              </div>
            ) : null}
          </div>
        </div>
      ),
    }));
  }, []);
  const getDetail = () => {
    getDriverCardDetail(curCardId)
      .then((res: any) => {
        const { data } = res;
        console.log(data, '打印看看');
        data.trainRecordVoList.map((v: any) => {
          const time = v.signInTime.slice(0, 10);
          const timeArry = time?.split('-') || [];
          v.labelTime = timeArry[0] + '年' + timeArry[1] + '月' + timeArry[2] + '日';
        });
        const tempTimeLineItems = setTimeLineItemsFn(data.trainRecordVoList || []);
        setTimeLineItems(tempTimeLineItems);

        setCardDetail(data);
      })
      .catch((err: any) => {
        console.log('DriverCardDetail--studyCard/statisticsStudyCardDetails--err--:', err);
      })
      .finally(() => {
        setLoading(false);
      });
  };
  //点击modal保存按钮
  const confirmModal = () => {
    setModalBtnStatus({ disabled: true, loading: true });
    EditExpireRef.current?.onSubmit().then((values: any) => {
      const upTime = values.endTime.format('YYYY-MM-DD');
      confirm({
        title: '提示',
        width: '450px',
        content: '您确定要更改 ' + values.personName + ' 的学习卡有效期至 ' + upTime + ' 吗？',
        centered: true,
        onOk: () => {
          editExpireApi({ ...values, upTime }).then((res: any) => {
            if (res.code == 200) {
              message.success('修改成功');
              getDetail();
              closeModal();
              refreshTable();
            }
          });
        },
      });
    });
    // .finally(() => {
    //   setModalBtnStatus({ disabled: false, loading: false });
    //   closeModal();
    // });
    setModalBtnStatus({ disabled: false, loading: false });
  };
  // modal框配置
  const modalConst = {
    open: isModalShow.show,
    width: 450,
    // centered: true,
    destroyOnClose: true,
    footer: [
      <Button key="back" disabled={modalBtnStatus.disabled} onClick={closeModal}>
        取消
      </Button>,
      <Button type="primary" key="save" loading={modalBtnStatus.loading} onClick={confirmModal}>
        保存
      </Button>,
    ],
    onCancel: closeModal,
  };
  useEffect(() => {
    if (!curCardId) return;
    setLoading(true);
    getDetail();
  }, [curCardId]);

  return (
    <div>
      <CusModal {...modalConst} {...configModal} />
      {!isEmpty(cardDetail) && (
        <Spin spinning={loading}>
          <Descriptions
            title="基本信息"
            labelStyle={{ width: 56, justifyContent: 'flex-start' }}
            column={2}
            className="ym_descriptions"
          >
            <Descriptions.Item label="姓名" span={1}>
              {cardDetail.personName}
            </Descriptions.Item>
            <Descriptions.Item label="电话" span={1}>
              {cardDetail.phone}
            </Descriptions.Item>
            <Descriptions.Item label="企业" span={1}>
              {cardDetail.entName}
            </Descriptions.Item>
          </Descriptions>
          <Descriptions
            title="学习卡情况"
            labelStyle={{ width: 56, justifyContent: 'flex-start' }}
            column={2}
            className="ym_descriptions"
          >
            <Descriptions.Item label="状态" span={1}>
              {cardDetail.state == 1 ? (
                <span style={{ color: '#33CC67', display: 'flex', alignItems: 'center' }}>
                  <span
                    style={{
                      display: 'inline-block',
                      width: 4,
                      height: 4,
                      background: '#33CC67',
                      borderRadius: '8px',
                      marginRight: 3,
                    }}
                  ></span>
                  正常
                </span>
              ) : (
                <span style={{ color: '#999999', display: 'flex', alignItems: 'center' }}>
                  <span
                    style={{
                      display: 'inline-block',
                      width: 4,
                      height: 4,
                      background: '#999999',
                      borderRadius: '8px',
                      marginRight: 3,
                    }}
                  ></span>
                  已过期
                </span>
              )}
            </Descriptions.Item>
            <Descriptions.Item label="有效期" span={1}>
              <div>
                {cardDetail.startTime || '--'}&nbsp;&nbsp;至&nbsp;&nbsp;{cardDetail.endTime || '--'}
                <span
                  style={{ cursor: 'pointer', color: '#1890ff', marginLeft: 20 }}
                  onClick={() => openEditExpirModal({ ...cardDetail, studyCardId: curCardId })}
                >
                  修改
                </span>
              </div>
            </Descriptions.Item>
          </Descriptions>
          <Descriptions
            title="培训记录"
            labelStyle={{ width: 72, justifyContent: 'flex-end' }}
            column={1}
            className="ym_descriptions"
          >
            <>
              {!isEmpty(timeLineItems) ? (
                <div className={OStyle.pxTimeLine}>
                  <Timeline items={timeLineItems} />
                </div>
              ) : (
                <div className="flexr alc juc">
                  <Empty />
                </div>
              )}
            </>
          </Descriptions>
        </Spin>
      )}
    </div>
  );
}

export default DriverCardDetail;
